package goods

import (
	"context"
	"fmt"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/goods_web/api"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/goods_web/forms"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/goods_web/global"
	"gitee.com/DonHz/electronic-business-systems/mxshop-api/goods_web/proto"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strconv"
)

func List(ctx *gin.Context) {
	req := &proto.GoodsFilterRequest{}

	priceMinStr := ctx.DefaultQuery("pmin", "0")
	priceMin, _ := strconv.Atoi(priceMinStr)
	req.PriceMin = int32(priceMin)
	priceMaxStr := ctx.DefaultQuery("pmax", "100")
	priceMax, _ := strconv.Atoi(priceMaxStr)
	req.PriceMax = int32(priceMax)
	isHot := ctx.DefaultQuery("ih", "0")
	if isHot == "1" {
		req.IsHot = true
	}
	isNew := ctx.DefaultQuery("in", "0")
	if isNew == "1" {
		req.IsNew = true
	}
	isTab := ctx.DefaultQuery("it", "0")
	if isTab == "1" {
		req.IsTab = true
	}
	categoryIdStr := ctx.DefaultQuery("c", "0")
	categoryId, _ := strconv.Atoi(categoryIdStr)
	req.TopCategory = int32(categoryId)
	pageStr := ctx.DefaultQuery("pn", "0")
	page, _ := strconv.Atoi(pageStr)
	req.Pages = int32(page)
	pageNumStr := ctx.DefaultQuery("pnum", "10")
	pageNum, _ := strconv.Atoi(pageNumStr)
	req.Pages = int32(pageNum)
	keywords := ctx.DefaultQuery("q", "")
	req.KeyWords = keywords
	brandsIdStr := ctx.DefaultQuery("b", "0")
	brandsId, _ := strconv.Atoi(brandsIdStr)
	req.Brand = int32(brandsId)

	// 请求商品服务
	resp, err := global.GoodsSrvClient.GoodsList(context.Background(), req)
	fmt.Println(resp.Data)
	if err != nil {
		zap.L().Error("【GoodsList】获取商品列表失败", zap.Error(err))
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	reMap := map[string]interface{}{
		"total": resp.Total,
	}
	goodsList := make([]interface{}, 0)
	for _, value := range resp.Data {
		goodsList = append(goodsList, map[string]interface{}{
			"id":           value.Id,
			"name":         value.Name,
			"goods_brief":  value.GoodsBrief,
			"desc":         value.GoodsDesc,
			"ship_free":    value.ShipFree,
			"clickNum":     value.ClickNum,
			"soldNum":      value.SoldNum,
			"favNum":       value.FavNum,
			"marketPrice":  value.MarketPrice,
			"shopPrice":    value.ShopPrice,
			"images":       value.Images,
			"descImages":   value.DescImages,
			"front_images": value.GoodsFrontImage,
			"on_sale":      value.OnSale,
			"category": map[string]interface{}{
				"id":   value.Category.Id,
				"name": value.Category.Name,
			},
			"brand": map[string]interface{}{
				"id":   value.Brand.Id,
				"name": value.Brand.Name,
				"logo": value.Brand.Logo,
			},
			"is_hot": value.IsHot,
			"is_new": value.IsNew,
		})
	}
	reMap["data"] = goodsList
	ctx.JSON(http.StatusOK, reMap)
}

func New(ctx *gin.Context) {
	var goodsForm forms.GoodsForm
	if err := ctx.ShouldBindJSON(&goodsForm); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	goodsClient := global.GoodsSrvClient
	resp, err := goodsClient.CreateGoods(context.Background(), &proto.CreateGoodsInfo{
		Name:            goodsForm.Name,
		GoodsSn:         goodsForm.GoodsSn,
		Stocks:          int64(goodsForm.Stocks),
		MarketPrice:     goodsForm.MarketPrice,
		ShopPrice:       goodsForm.ShopPrice,
		GoodsBrief:      goodsForm.GoodsBrief,
		ShipFree:        *goodsForm.ShipFree,
		Images:          goodsForm.Images,
		DescImages:      goodsForm.DescImages,
		GoodsFrontImage: goodsForm.FrontImage,
		CategoryId:      int64(goodsForm.CategoryId),
		BrandId:         int64(goodsForm.Brand),
	})
	if err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}
	fmt.Println(resp)
	// 如何设置库存
	// TODO
	// 成功返回
	ctx.JSON(http.StatusOK, resp)
}

func Detail(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, "参数错误")
		return
	}
	r, err := global.GoodsSrvClient.GetGoodsDetail(context.Background(), &proto.GoodInfoRequest{
		Id: id,
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, c)
		return
	}
	resp := map[string]interface{}{
		"id":           r.Id,
		"name":         r.Name,
		"goods_brief":  r.GoodsBrief,
		"desc":         r.GoodsDesc,
		"ship_free":    r.ShipFree,
		"clickNum":     r.ClickNum,
		"soldNum":      r.SoldNum,
		"favNum":       r.FavNum,
		"marketPrice":  r.MarketPrice,
		"shopPrice":    r.ShopPrice,
		"images":       r.Images,
		"descImages":   r.DescImages,
		"front_images": r.GoodsFrontImage,
		"on_sale":      r.OnSale,
		"category": map[string]interface{}{
			"id":   r.Category.Id,
			"name": r.Category.Name,
		},
		"brand": map[string]interface{}{
			"id":   r.Brand.Id,
			"name": r.Brand.Name,
			"logo": r.Brand.Logo,
		},
		"is_hot": r.IsHot,
		"is_new": r.IsNew,
	}
	c.JSON(http.StatusOK, resp)
}

func Delete(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, "参数错误")
		return
	}
	_, err = global.GoodsSrvClient.DeleteGoods(context.Background(), &proto.DeleteGoodsInfo{
		Id: id,
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, c)
		return
	}
	c.JSON(http.StatusOK, "成功删除")
}

func Stocks(c *gin.Context) {
	idStr := c.Param("id")
	_, err := strconv.ParseInt(idStr, 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, "参数错误")
		return
	}
	// TODO 商品库存
	return
}

func UpdateStatus(c *gin.Context) {
	var goodsForm forms.GoodsStatusForm
	if err := c.ShouldBindJSON(&goodsForm); err != nil {
		api.HandleValidatorError(c, err)
		return
	}
	idStr := c.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, "参数错误")
		return
	}
	_, err = global.GoodsSrvClient.UpdateGoods(context.Background(), &proto.CreateGoodsInfo{
		Id:     id,
		IsNew:  *goodsForm.IsNew,
		IsHot:  *goodsForm.IsHot,
		OnSale: *goodsForm.OnSale,
	})
	if err != nil {
		api.HandleValidatorError(c, err)
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"msg": "修改成功",
	})
}

func Update(c *gin.Context) {
	var goodsForm forms.GoodsForm
	if err := c.ShouldBindJSON(&goodsForm); err != nil {
		api.HandleValidatorError(c, err)
		return
	}
	idStr := c.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, "参数错误")
		return
	}
	_, err = global.GoodsSrvClient.UpdateGoods(context.Background(), &proto.CreateGoodsInfo{
		Id:              id,
		Name:            goodsForm.Name,
		GoodsSn:         goodsForm.GoodsSn,
		Stocks:          int64(goodsForm.Stocks),
		MarketPrice:     goodsForm.MarketPrice,
		ShopPrice:       goodsForm.ShopPrice,
		GoodsBrief:      goodsForm.GoodsBrief,
		ShipFree:        *goodsForm.ShipFree,
		Images:          goodsForm.Images,
		DescImages:      goodsForm.DescImages,
		GoodsFrontImage: goodsForm.FrontImage,
		CategoryId:      int64(goodsForm.CategoryId),
		BrandId:         int64(goodsForm.Brand),
	})
	if err != nil {
		api.HandleValidatorError(c, err)
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"msg": "更新成功",
	})
}
